package com.jt.www.queue.issue;

import com.jt.www.dao.mapper.issue.mapper.MqMessageEntityMapper;
import com.jt.www.model.issue.entity.MqMessageEntity;
import com.jt.www.queue.process.ElecPolicyProcess;
import com.rabbitmq.client.Channel;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;


@Component
public class ElecPolicyMsglistenerTest {

    public static final Logger log = LoggerFactory.getLogger(ElecPolicyMsglistenerTest.class);

    @Autowired
    MqMessageEntityMapper mqMessageEntityMapper;

    @Autowired
    ElecPolicyProcess elecPolicyProcess;

    // dev环境注释掉  test放开
    //@RabbitListener(queues = "${jtpf.rabbit.queuename.epolicy}")
    public void processMsg(Message msg, Channel channel) {
        Long logId = System.currentTimeMillis();

        log.info("{}:ElecPolicyMsglistener get MessageProperties  {}", logId, msg.getMessageProperties().toString());
        log.info("{}:ElecPolicyMsglistener get MessageBody  {}", logId, new String(msg.getBody()));

        byte[] msgbody = msg.getBody();
        if (msgbody == null || msgbody.length == 0) {
            log.info("{}:返回报文为空 {} {}", logId, msg.getMessageProperties().getReceivedExchange(), msg.getMessageProperties().getReceivedRoutingKey());
            try {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("{}:ACK确认出错，出错信息为", logId, e);
            }
            return;
        }
        try {
            // 字节数组转换为输入流
            InputStream is = new ByteArrayInputStream(msgbody);
            // 解析xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(is);
            Element rootElement = document.getRootElement();
            String ifCode = msg.getMessageProperties().getHeaders().get("IfCode").toString();

            //添加消息记录入库 并直接返回 ack
            MqMessageEntity mqMessageEntity = new MqMessageEntity();
            mqMessageEntity.setIfCode(ifCode);
            mqMessageEntity.setMessage(rootElement.asXML());
            mqMessageEntity.setCreateTime(new Date());
            mqMessageEntityMapper.insert(mqMessageEntity);
            processMqMessage(rootElement, ifCode, logId);
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("{}:ElecPolicyMsglistenerTest出错，出错信息为", logId, ex);
        } finally {
            try {
                channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                log.error("{}:ACK确认出错，出错信息为", logId, e);
            }
        }
    }

    /**
     * 处理消息
     *
     * @param rootElement
     * @param logId
     */
    public void processMqMessage(Element rootElement, String ifCode, Long logId) throws Exception {
        log.info("{}:解析的消息：{}", logId, rootElement.asXML());
        elecPolicyProcess.process(rootElement, ifCode);
    }
}
